#include "wl_semaphore.h"

#include "wl_trace.h"

#include <errno.h>
#include <fcntl.h>
#include <pthread.h>

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

wl_int32 wl_semaphore_create(const wl_char* name, OUT WL_SEMAPHORE* semaphore, wl_uint32 init_count) {
    if (wl_null != semaphore) {
        UNUSED(name);
        sem_unlink(name);
        if (0 != ak_thread_sem_init(semaphore, 0)) {
            WLLOGW("sem_open fail");
            return -1;
        }
        return 0;
    }
    return -1;
}

wl_int32 wl_semaphore_wait(WL_SEMAPHORE* semaphore) {
    if (wl_null != semaphore) {
        if (0 != ak_thread_sem_wait(semaphore)) {
            WLLOGW("sem_wait fail");
            return -1;
        }
        return 0;
    }

    return -1;
}

wl_int32 wl_semaphore_try_wait(WL_SEMAPHORE* semaphore, wl_uint32 timeout) {
    if (wl_null != semaphore) {
        UNUSED(timeout);
        if (0 != ak_thread_sem_trywait(semaphore)) {
            WLLOGW("sem_wait fail");
            return -1;
        }
        return 0;
    }
    return -1;
}

wl_int32 wl_semaphore_post(WL_SEMAPHORE* semaphore) {
    if (wl_null != semaphore) {
        if (0 != ak_thread_sem_post(semaphore)) {
            WLLOGW("sem_post fail");
            return -1;
        }
        return 0;
    }
    return -1;
}

wl_int32 wl_semaphore_delete(WL_SEMAPHORE* semaphore) {
    if (wl_null != semaphore) {
        if (0 != ak_thread_sem_destroy(semaphore)) {
            WLLOGW("sem_destroy fail");
            return -1;
        }
        return 0;
    }
    return -1;
}

#ifdef __cplusplus
}
#endif /* __cplusplus */
